<template>
  <div class="my-favorites">
    <!-- 筛选工具栏 -->
    <div class="filter-toolbar bg-white p-4 rounded-lg shadow-sm mb-6">
      <div class="flex flex-wrap gap-4">
        <!-- 排序选项 -->
        <el-radio-group v-model="sortBy" @change="handleSortChange">
          <el-radio-button label="newest">最新收藏</el-radio-button>
          <el-radio-button label="oldest">最早收藏</el-radio-button>
        </el-radio-group>

        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索收藏内容"
          class="w-64"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <!-- 批量操作 -->
        <div class="flex-1 flex justify-end">
          <el-button
            type="danger"
            :disabled="!selectedItems.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="favorites-list" v-loading="loading">
      <el-table
        v-model:selected="selectedItems"
        :data="favoritesList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column label="内容" min-width="300">
          <template #default="{ row }">
            <div class="flex items-start gap-4">
              <!-- 缩略图 -->
              <div v-if="row.media?.length" class="flex-shrink-0">
                <el-image
                  :src="row.media[0]"
                  class="w-20 h-20 rounded-lg object-cover"
                  :preview-src-list="row.media"
                />
              </div>

              <!-- 文本内容 -->
              <div class="flex-1 min-w-0">
                <div class="text-sm line-clamp-2">{{ row.content }}</div>
                <div class="mt-2 flex items-center text-xs text-gray-500">
                  <span>{{ row.author.nickname }}</span>
                  <el-divider direction="vertical" />
                  <span>{{ formatTime(row.createTime) }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="收藏时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.favoriteTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleView(row)">
                查看
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-wrapper flex justify-center mt-8">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && !favoritesList.length"
        description="暂无收藏内容"
      >
        <el-button @click="handleExplore">去发现</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();

// 列表数据
const favoritesList = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const sortBy = ref("newest");
const searchQuery = ref("");
const selectedItems = ref([]);

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 获取收藏列表
const getFavoritesList = async () => {
  loading.value = true;
  try {
    // TODO: 调用获取收藏列表API
    const response = await new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          items: [
            {
              id: 1,
              content: "这是一条收藏的动态内容...",
              media: ["/images/posts/example.jpg"],
              author: {
                id: 1,
                nickname: "用户昵称",
              },
              createTime: "2024-03-15 10:00:00",
              favoriteTime: "2024-03-15 12:00:00",
            },
          ],
          total: 100,
        });
      }, 500);
    });

    favoritesList.value = response.items;
    total.value = response.total;
  } catch (error) {
    console.error("获取收藏列表失败:", error);
    ElMessage.error("获取收藏列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  getFavoritesList();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getFavoritesList();
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection;
};

// 处理查看
const handleView = (item) => {
  router.push(`/community/post/${item.id}`);
};

// 处理删除
const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm("确定要删除这条收藏吗？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // TODO: 调用删除收藏API
    await new Promise((resolve) => setTimeout(resolve, 500));

    ElMessage.success("删除成功");
    getFavoritesList();
  } catch {
    // 用户取消操作
  }
};

// 处理批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedItems.value.length} 条收藏吗？`,
      "批量删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // TODO: 调用批量删除API
    await new Promise((resolve) => setTimeout(resolve, 500));

    ElMessage.success("删除成功");
    getFavoritesList();
  } catch {
    // 用户取消操作
  }
};

// 处理去发现
const handleExplore = () => {
  router.push("/community");
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getFavoritesList();
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getFavoritesList();
};

// 页面加载时获取数据
onMounted(() => {
  getFavoritesList();
});
</script>

<style lang="scss" scoped>
.my-favorites {
  .filter-toolbar {
    :deep(.el-radio-group) {
      @apply flex flex-wrap gap-2;
    }
  }

  .favorites-list {
    :deep(.el-table) {
      @apply rounded-lg overflow-hidden;
    }
  }
}
</style>
